import request from './request';

const API_BASE_PATH = '/api/dta';

/**
 * 获取销售预测结果
 * @param {Object} params - 请求参数
 * @param {string} params.method - 预测方法：'moving_average', 'exponential_smoothing', 'linear_trend'
 * @param {number} params.months - 使用历史数据的月数
 * @returns {Promise<Object>} 销售预测结果
 */
export function predictSales(params) {
  console.log('调用销售预测API, 参数:', params);
  return request({
    url: `${API_BASE_PATH}/sales/predict/`,
    method: 'get',
    params
  }).then(response => {
    console.log('销售预测API返回:', response);
    return response;
  }).catch(error => {
    console.error('销售预测API错误:', error);
    // 返回模拟数据
    return {
      current_month: new Date().toISOString().slice(0, 7),
      next_month: new Date(new Date().setMonth(new Date().getMonth() + 1)).toISOString().slice(0, 7),
      current_month_amount: 125000.00,
      prediction: 135000.00,
      confidence_interval: 8.5,
      lower_bound: 123525.00,
      upper_bound: 146475.00,
      growth_rate: 8.0,
      accuracy: 92.5,
      method: params.method || 'moving_average',
      sales_data: generateMockSalesData(12)
    };
  });
}

/**
 * 获取历史销售数据
 * @param {Object} params - 请求参数
 * @param {number} params.months - 历史数据月数
 * @returns {Promise<Object>} 历史销售数据
 */
export function getHistoricalSales(params) {
  console.log('调用历史销售数据API, 参数:', params);
  return request({
    url: `${API_BASE_PATH}/sales/historical/`,
    method: 'get',
    params
  }).then(response => {
    console.log('历史销售数据API返回:', response);
    return response;
  }).catch(error => {
    console.error('历史销售数据API错误:', error);
    // 返回模拟数据
    return {
      sales_data: generateMockHistoricalData(params.months || 24),
      total_months: params.months || 24
    };
  });
}

/**
 * 获取销售季节性分析数据
 * @returns {Promise<Object>} 季节性数据
 */
export function getSalesSeasonality() {
  console.log('调用销售季节性分析API');
  return request({
    url: `${API_BASE_PATH}/sales/seasonality/`,
    method: 'get'
  }).then(response => {
    console.log('销售季节性分析API返回:', response);
    return response;
  }).catch(error => {
    console.error('销售季节性分析API错误:', error);
    // 返回模拟数据
    return {
      seasonality_data: generateMockSeasonalityData()
    };
  });
}

/**
 * 获取产品销售预测对比数据
 * @returns {Promise<Object>} 产品销售对比数据
 */
export function getProductSalesComparison() {
  console.log('调用产品销售对比API');
  return request({
    url: `${API_BASE_PATH}/sales/product-comparison/`,
    method: 'get'
  }).then(response => {
    console.log('产品销售对比API返回:', response);
    return response;
  }).catch(error => {
    console.error('产品销售对比API错误:', error);
    // 返回模拟数据
    return {
      product_comparison: generateMockProductComparison()
    };
  });
}

/**
 * 获取预测误差分析数据
 * @returns {Promise<Object>} 预测误差分析数据
 */
export function getPredictionErrorAnalysis() {
  console.log('调用预测误差分析API');
  return request({
    url: `${API_BASE_PATH}/sales/error-analysis/`,
    method: 'get'
  }).then(response => {
    console.log('预测误差分析API返回:', response);
    return response;
  }).catch(error => {
    console.error('预测误差分析API错误:', error);
    // 返回模拟数据
    return {
      error_data: generateMockErrorData(),
      mae: 4.5,
      rmse: 5.8,
      error_distribution: {
        excellent: 2, // 误差在0-3%
        good: 1,      // 误差在3-5%
        fair: 2,      // 误差在5-8%
        poor: 1       // 误差大于8%
      }
    };
  });
}

// 辅助函数：生成模拟销售数据
function generateMockSalesData(months = 12) {
  const data = [];
  const today = new Date();
  let baseAmount = 100000;
  
  for (let i = months - 1; i >= 0; i--) {
    const date = new Date(today.getFullYear(), today.getMonth() - i, 1);
    const month = date.toISOString().slice(0, 7);
    
    // 添加一些随机波动
    const fluctuation = 0.9 + Math.random() * 0.2; // 0.9到1.1之间的随机数
    baseAmount = baseAmount * fluctuation;
    
    data.push({
      month: month,
      amount: Math.round(baseAmount * 100) / 100
    });
  }
  
  return data;
}

// 辅助函数：生成模拟历史销售数据
function generateMockHistoricalData(months = 24) {
  const data = [];
  const today = new Date();
  let baseAmount = 95000;
  let prevAmount = null;
  
  for (let i = months - 1; i >= 0; i--) {
    const date = new Date(today.getFullYear(), today.getMonth() - i, 1);
    const month = date.toISOString().slice(0, 7);
    
    // 添加一些随机波动
    const fluctuation = 0.92 + Math.random() * 0.16; // 0.92到1.08之间的随机数
    baseAmount = baseAmount * fluctuation;
    
    // 季节性因素 - 第四季度销售额通常较高
    const monthNum = date.getMonth() + 1;
    let seasonalFactor = 1.0;
    if (monthNum >= 10) { // 10, 11, 12月
      seasonalFactor = 1.2;
    } else if (monthNum <= 2) { // 1, 2月
      seasonalFactor = 0.85;
    }
    
    const amount = baseAmount * seasonalFactor;
    
    // 计算环比增长率
    let momGrowth = null;
    if (prevAmount !== null) {
      momGrowth = ((amount - prevAmount) / prevAmount) * 100;
    }
    
    // 假设数据
    const productSales = amount * 0.7; // 产品销售占70%
    const rentalIncome = amount * 0.3; // 租赁收入占30%
    
    data.push({
      month: month,
      total: Math.round(amount * 100) / 100,
      product_sales: Math.round(productSales * 100) / 100,
      rental_income: Math.round(rentalIncome * 100) / 100,
      mom_growth: momGrowth !== null ? Math.round(momGrowth * 10) / 10 : null,
      yoy_growth: Math.round((Math.random() * 20 - 5) * 10) / 10, // -5% 到 15% 之间的随机值
      order_count: Math.floor(amount / 8000 + Math.random() * 5),
      prediction_error: Math.round((Math.random() * 16 - 8) * 10) / 10 // -8% 到 8% 之间的随机值
    });
    
    prevAmount = amount;
  }
  
  return data;
}

// 辅助函数：生成模拟季节性数据
function generateMockSeasonalityData() {
  const currentYear = new Date().getFullYear();
  const years = [currentYear - 2, currentYear - 1, currentYear, currentYear + 1];
  const result = [];
  
  // 基本月度模式
  const basePattern = [
    80000, 75000, 85000, 90000, 95000, 105000, 
    110000, 100000, 95000, 120000, 130000, 140000
  ];
  
  // 为每年生成数据
  years.forEach((year, yearIndex) => {
    const yearData = [];
    const growthFactor = 1 + yearIndex * 0.1; // 每年增长10%
    const isPrediction = year > currentYear;
    
    for (let month = 1; month <= 12; month++) {
      const baseAmount = basePattern[month - 1] * growthFactor;
      // 添加随机波动，预测数据波动更大
      const fluctuation = isPrediction ? 
        0.85 + Math.random() * 0.3 : // 预测数据波动: 0.85-1.15
        0.95 + Math.random() * 0.1;  // 历史数据波动: 0.95-1.05
      
      yearData.push({
        month: month,
        amount: Math.round(baseAmount * fluctuation * 100) / 100
      });
    }
    
    result.push({
      year: year,
      data: yearData,
      is_prediction: isPrediction
    });
  });
  
  return result;
}

// 辅助函数：生成模拟产品销售对比数据
function generateMockProductComparison() {
  const products = [
    { name: '智能办公套件', base: 320000 },
    { name: '企业财务系统', base: 280000 },
    { name: '物流跟踪平台', base: 250000 },
    { name: '数据分析工具', base: 200000 },
    { name: '安全防护系统', base: 180000 },
    { name: '主机租赁', base: 150000 }
  ];
  
  return products.map(product => {
    const actualAmount = product.base * (0.95 + Math.random() * 0.1);
    const growthRate = 1.05 + Math.random() * 0.1; // 5%-15%的增长
    
    return {
      product_name: product.name,
      actual_amount: Math.round(actualAmount * 100) / 100,
      predicted_amount: Math.round(actualAmount * growthRate * 100) / 100
    };
  });
}

// 辅助函数：生成模拟误差数据
function generateMockErrorData() {
  const data = [];
  const today = new Date();
  
  for (let i = 6; i > 0; i--) {
    const date = new Date(today.getFullYear(), today.getMonth() - i, 1);
    const month = date.toISOString().slice(0, 7);
    
    // 随机误差率，范围-10%到10%
    const errorRate = Math.round((Math.random() * 20 - 10) * 10) / 10;
    
    data.push({
      month: month,
      error_rate: errorRate
    });
  }
  
  return data;
} 